package com.qianli.cashmama.product.server.config;

import com.qianli.cashmama.product.server.controller.pay2.http.MySocketFactoryRegistry;
import com.qianli.cashmama.product.server.controller.pay2.http.PooledHttpService;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BeanConfiguration {

    @Bean
    protected PooledHttpService initHttpService() {
        try {
            PoolingHttpClientConnectionManager httpClientConnectionManager =
                    new PoolingHttpClientConnectionManager(new MySocketFactoryRegistry().createRegistry());
            httpClientConnectionManager.setMaxTotal(50);
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            httpClientBuilder.setConnectionManager(httpClientConnectionManager);
            CloseableHttpClient httpClient = httpClientBuilder.build();
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();

            PooledHttpService pooledHttpService = new PooledHttpService();
            pooledHttpService.setCloseableHttpClient(httpClient);
            pooledHttpService.setRequestConfig(requestConfig);
            return pooledHttpService;
        } catch (Exception e) {
            return null;
        }

    }
}
